#!/bin/sh
# SYNOPSIS:
#    bak [OPT]... [FILE]...
#
# USAGE:
#     Backup and zip files for later restoration to the same path. 
# 
# OPTIONS:
#     -d DIR - specify directory to back up to or restore from.
#
#     -z CMD - specify zip/archive tool.
# 
# ENV:
#     BAK_DIR - set default backup directory for bak. default is $home/.backup.
# 
#     BAK_ZIP - set default archive tool. Default is pigz.
#
#     BAK_UNZIP - set default extraction tool. Default is unpigz.
# 
# END_H


shimport core

main ()
{
    # Pull env.
    bak_dir=$BAK_DIR
    bak_zip=$BAK_ZIP
    bak_unzip=$BAK_UNZIP

    # Set defaults if env is not set.
    test -z $bak_dir   && bak_dir="$home/.backup"
    test -z $bak_zip   && bak_zip=pigz
    test -z $bak_unzip && bak_unzip=unpigz

    mode=backup

    while getopts 'hd:z:rs' OPT; do
        case $OPT in
            d) bak_dir="$OPTARG" ;; 
            z) bak_zip="$OPTARG" ;;
            r) mode=restore      ;;
            h) usage; exit 0     ;;
            :) usage; invalid_optarg $OPT ;;
            ?) usage; invalid_opt    $OPT ;;
        esac 
    done
    shift $((OPTIND-1))
    mkdir -p "$bak_dir"

    test $mode = restore && targets="$(search $@)" \
                         || targets="$@"
    for i in $targets;
        $mode $i
    done

    exit 0
}


backup ()
{ 
    filepath=$(realpath $i)
    filename="$(echo $filepath | sed 's\/\>\g')"
    log "Backing up $filepath to $bak_dir and compressing with $bak_zip."
    \cp -pr "$filepath" "$bak_dir/$filename"
    $bak_zip "$bak_dir/$filename"  
}


restore ()
{
    cd $bak_dir
    $bak_unzip $i
    unzipped_file='$(echo $i | sed 's/\.gz//') 
    restore_dest=$(echo $unzipped_file | sed 's\>\/\;s')
    log "Restoring $restore_dest."
    mv -f $unzipped_file $restore_dest
    cd -
}


list_all ()
{
    echo $bak_dir/*       | \
    sed -e 's\$bak_dir\\'   \
        -e 's\>\/\'         \
        -e 's/\.gz$//'    | \
    xargs -n1 echo
}


search () { list_all | grep $@; }


main $@
